package com.muyan.amqp;

import com.muyan.utils.MQConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: YLTDMenglc
 * @Date: 2019/6/19
 * @Time: 14:13
 * @Description:    消息确认机制：1、AMQP事务机制
 */
public class AMQPProducer {

    private static final String QUEUE_NAME = "test_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = MQConnectionUtils.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        // 将当前管道设置为 txSelect 将当前channel设置为transaction模式 开启事务
        channel.txSelect();
        String msg = "test_yushengjun110";
        try {
            channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
//            int i = 1 / 0;
            channel.txCommit();
            System.out.println("生产者发送消息:" + msg);
        } catch (Exception e){
            e.printStackTrace();
            System.out.println("消息进行回滚操作");
            channel.txRollback();
        } finally {
            channel.close();
            connection.close();
        }
    }
}
